package com.swind.fast.modules.app.space.rent.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// import com.swind.fast.modules.app.railway.project.constant.ProjectStatusEnum;

import com.swind.fast.common.api.vo.Result;
import com.swind.fast.common.system.query.QueryGenerator;
import com.swind.fast.common.util.oConvertUtils;
// import com.swind.fast.modules.app.railway.project.entity.RailwayProject;
// import com.swind.fast.modules.app.railway.project.vo.RailwayProjectVo;
// import com.swind.fast.modules.app.railway.project.service.IRailwayProjectService;
// import com.swind.fast.modules.app.railway.project.vo.RailwayProjectVo;
// import com.swind.fast.modules.app.railway.project.vo.RailwayProjectStatisticVo;
// import com.swind.fast.modules.app.railway.project.vo.RailwayDataManagementStatisticVo;
// import com.swind.fast.modules.app.railway.project.entity.RailwayProjectOperationLog;

import com.swind.fast.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;

import com.swind.fast.common.constant.CommonConstant;
import com.swind.fast.common.util.CommonUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.swind.fast.modules.app.space.rent.component.SpaceComponent;
import com.swind.fast.modules.app.space.rent.vo.SpaceDashboardStatisticVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.swind.fast.modules.app.space.rent.util.WordToHtmlUtil;

import com.swind.fast.modules.oss.entity.OSSFile;
import com.swind.fast.modules.oss.service.IOSSFileService;
import org.springframework.util.FileCopyUtils;

import com.swind.fast.modules.app.space.rent.component.SpaceInvokeComponent;

import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.HashMap;
import java.io.*;

@RestController
@RequestMapping("/app/space/home")
@Api(tags="首页模块")
@Slf4j
public class SpaceHomeController {

    @Autowired
    private SpaceComponent spaceComponent;

    @Autowired
    private SpaceInvokeComponent spaceInvokeComponent;

    @Autowired
    private IOSSFileService ossFileService;

    @Value(value = "${swind.path.upload}")
    private String uploadpath;

    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value="${swind.uploadType}")
    private String uploadType;

    @ApiOperation(value="首页数据", notes="首页数据")
    @GetMapping(value = "/statistic")
    public Result<?> statisticAction() {
        // RailwayProjectStatisticVo resp = railwayProjectService.getProjectStatistic();
        SpaceDashboardStatisticVo resp = spaceComponent.getDashboardData();
        return Result.OK("成功!", resp);
    }

    // @GetMapping(value = "/data/statistic")
    // public Result<?> dataStatisticAction(@RequestParam(name = "projectId", required = true) String projectId) {
    //     RailwayDataManagementStatisticVo resp = railwayProjectService.getDataManagementStatistic(projectId);
    //     return Result.OK("成功!", resp);
    // }

    // @ApiOperation("更新项目状态")
    // @PostMapping(value = "/status/update")
    // public Result<?> statusUpdate(@RequestBody RailwayProjectOperationLog railwayProject) {
    //     // log.info("railwayProject: {}, name: {}", railwayProject, railwayProject.getName());
    //     railwayProjectService.updateProjectStatus(railwayProject);
    //     return Result.OK("成功！");
    // }

    @ApiOperation(value="数据测试", notes="首页数据测试")
    @PostMapping(value = "/file/parse")
    public Result<?> fileParseAction(@RequestBody OSSFile ossFile) {
        // RailwayProjectStatisticVo resp = railwayProjectService.getProjectStatistic();
        // SpaceDashboardStatisticVo resp = spaceComponent.getDashboardData();
        String filePath = ossFile.getFurl();
        log.info("filePath: {}", ossFile);
        // String filePath = "/opt/upload/applyInfo.docx";
        String html = "";
        try {
            html = WordToHtmlUtil.docxToHtmlText(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.OK("成功!", html);
    }

    @PostMapping(value = "/space/upload")
    public Result<?> spaceUpload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if (oConvertUtils.isEmpty(bizPath)) {
            if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
                //result.setMessage("使用阿里云文件上传时，必须添加目录！");
                //result.setSuccess(false);
                //return result;
            }else{
                bizPath = "";
            }
        }
        if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            savePath = this.spaceUploadLocal(file, bizPath);
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            /**  富文本编辑器及markdown本地上传时，采用返回链接方式
            //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
            String jeditor = request.getParameter("jeditor");
            if(oConvertUtils.isNotEmpty(jeditor)){
                result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                result.setSuccess(true);
                return result;
            }else{
                savePath = this.uploadLocal(file,bizPath);
            }
            */
        } else {
            //update-begin-author:taoyan date:20200814 for:文件上传改造
            savePath = CommonUtils.upload(file, bizPath, uploadType);
            //update-end-author:taoyan date:20200814 for:文件上传改造
        }
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * @return
     */
    private String spaceUploadLocal(MultipartFile mf,String bizPath){
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }

            log.info("file: {}", savePath);

            String fpath = spaceInvokeComponent.parseAction(savePath);

            OSSFile ossFile = new OSSFile();
            ossFile.setFileName(orgName);
            ossFile.setUrl(savePath);
            ossFile.setFurl(fpath);
            ossFileService.save(ossFile);

            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

}
